<?php if(!defined('FRAME')) exit('No direct script access allowed');
/**
 * 应用App
 * @author wisoch@hotmail.com
 *
 */
class Application {

	private $applicationIni;

	private $autoLoader;
	
	private $controller = 'index';
	
	public function __construct($applicationIni) {
		$this->applicationIni = $applicationIni;
	}

	/**
	 * http
	 * @param unknown_type $application
	 */
	public function run($application) {
		$this->application = $application;
		
		include FRAME . '/Autoloader.php';
		$this->autoLoader = Autoloader::init($application);

		$config = Config::instance();
		$config->loadIni($this->applicationIni);

		//设置runtime环境
		if($config->get('runtime.env') == 'dev') {
			ini_set('display_errors', 1);
			error_reporting(E_ALL);
		};

		$this->dispath();
		
		//加载控制器
		$controller = trim($this->controller, '/');
		if(!$controller) $controller = 'index';
		$class = basename($controller);
		$filename = $this->application . '/controller/'.$controller.'.php';
		if(file_exists($filename)) {
			include $filename;
		} else {
			$filename = $this->application . '/controller/'.$controller.'/index.php';
			if(file_exists($filename)) {
				include $filename;
				$class = 'Index';
			} else {
				$ext = Uri::Instance()->getExt();
				
				if(strtolower($ext) == 'json') {
					echo json_encode(array('status' => 404, 'message' => 'Page Not Found'));
				} else {
					header("HTTP/1.0 404 Not Found");
					include($this->application . '/controller/error.php');
					new Error();
				}
				exit();
			}
		}
		
		new $class;
	}
	public function daemon($application) {
		$this->application = $application;
		
		include FRAME . '/Autoloader.php';
		$this->autoLoader = Autoloader::init($application);

		$config = Config::instance();
		$config->loadIni($this->applicationIni);

		//设置runtime环境
		if($config->get('runtime.env') == 'dev') {
			ini_set('display_errors', 1);
			error_reporting(E_ALL);
		};
	}
	private function dispath() {
		$uri = Uri::instance();
		$this->controller = $uri->resouce();
		if(!file_exists($this->application.'/config/route.php')) return $this;
		$routers = include $this->application.'/config/route.php';
		$route = new Route();
		foreach ($routers as $name => $router) {
			$route-> addRouter($name, $router);
		}
		if($uri->getExt()) {
			$result = $route->rewrite($this->controller.'.'.$uri->getExt());
			if($result) $this->controller = $result;
		} else $this->controller = $route->rewrite($this->controller);
		
		return $this;
	}
}